using Unity.Collections;
using Unity.Entities;
using Unity.Mathematics;
using Unity.Physics;
using Unity.Transforms;
using UnityEngine;

public class PlayerController : MonoBehaviour
{
    [SerializeField] Transform playerPoint;
    [SerializeField] float moveSpeed = 5f;
    EntityQuery entityQuery;
    NativeArray<Entity> entityArray;
    NativeArray<PhysicsVelocity> physicsVelocityArray;
    NativeArray<LocalTransform> localTransformArray;
    NativeArray<Player> playerArray;
    [SerializeField] GameObject bulletPrefab;

    Vector3 lastDir;
    void Update()
    {
        EntityManager entityManager = World.DefaultGameObjectInjectionWorld.EntityManager;

        float h = Input.GetAxis("Horizontal");
        float v = Input.GetAxis("Vertical");

        if(h != 0 || v != 0)
        {
            lastDir = new Vector3(h, 0, v);
        }
        Vector3 moveDir = new Vector3(h, 0, v) * moveSpeed * Time.fixedDeltaTime;


        entityQuery = new EntityQueryBuilder(Allocator.Temp).WithAll<PhysicsVelocity, LocalTransform, Unit>().WithPresent<Player>().Build(entityManager);
        entityArray = entityQuery.ToEntityArray(Allocator.Temp);
        physicsVelocityArray = entityQuery.ToComponentDataArray<PhysicsVelocity>(Allocator.Temp);
        localTransformArray = entityQuery.ToComponentDataArray<LocalTransform>(Allocator.Temp);
        playerArray = entityQuery.ToComponentDataArray<Player>(Allocator.Temp);
        Entity playerEntity = entityArray[0];
        PhysicsVelocity physicsVelocity = physicsVelocityArray[0];
        LocalTransform localTransform = localTransformArray[0];
        Player player = playerArray[0];
        physicsVelocity.Linear = moveDir; physicsVelocity.Angular = float3.zero;
        if(Input.GetKeyDown(KeyCode.T))
        {
            player.onShoot = true;
            player.shootDir = math.normalize(lastDir);
        }
        
        entityManager.SetComponentData(playerEntity, physicsVelocity);
        entityManager.SetComponentData(playerEntity, player);
        playerPoint.position = localTransform.Position;

        physicsVelocityArray.Dispose();
        localTransformArray.Dispose();
        playerArray.Dispose();
    }
}
